package com.bardpub.weblite 
{
	import com.bardpub.weblite.connect.WebRequest;
	import com.bardpub.weblite.system.WebConfig;
	import com.bardpub.weblite.ui.BaseLoadbar;
	import com.bardpub.weblite.ui.MainChildren;
	import com.bardpub.weblite.ui.Page;
	import com.bardpub.weblite.ui.PageInfo;
	import com.bardpub.weblite.utils.Broswer;
	import flash.debugger.enterDebugger;
	import flash.display.MovieClip;
	import flash.display.Sprite;
	import flash.display.StageAlign;
	import flash.display.StageScaleMode;
	import flash.events.Event;
	import flash.net.LocalConnection;
	import flash.system.System;
	import flash.utils.clearTimeout;
	import flash.utils.setTimeout;
	
	/**
	 * Copyright © 2010-2012, BardPub.com
	 * @fileName WebLiteMain.as
	 * @author LittleBard
	 * @version 1.0
	 * @date 2010/5/5
	 * @descrition 
	 * @others
	 * @history
	 */
	
	public class WebLiteMain extends MovieClip
	{
		protected var __currentPageInfo:PageInfo;
		protected var __currentPage:Page;
		protected var __children:MainChildren;
		protected var __loadBar:BaseLoadbar;
		private var __timeOut:Number;
		
		/**
		 * 创建 com.bardpub.weblite.WebLiteMain类 的新实例
		 */
		public function WebLiteMain() 
		{
			initialize();
		}
		
		/**********************************************************/
		/*===                                                  ===*/
		/*===         private/protected methods                ===*/
		/*===                                                  ===*/
		/**********************************************************/
		
		/**
		 * WebLiteMain初始化
		 */
		protected function initialize():void 
		{
			stage.align = StageAlign.TOP_LEFT;
			stage.scaleMode = StageScaleMode.NO_SCALE;
			stage.addEventListener(Event.RESIZE, onStageResize);
			WebConfig.getInstance().addEventListener(WebConfig.INVALIDATE, onWebConfigInit);
			WebConfig.getInstance().initialize(loaderInfo.parameters.config || "config.xml");
		}
		
		/**
		 * 开始渲染网站
		 */
		protected function invalidate():void 
		{
			
			//获取页面当前标签，并载入页面
			WebConfig.getInstance().goPage(WebConfig.getCurrentLocation());
		}
		
		

		
		
		/**
		 * 重新设置舞台坐标
		 */
		protected function resize(stageWidth:Number, stageHeight:Number):void 
		{
			if (__currentPage)
			{
				__currentPage.resize(stageWidth, stageHeight);
			}
			if (__children)
			{
				__children.resize(stageWidth, stageHeight);
			}
			if (__loadBar)
			{
				__loadBar.resize(stageWidth, stageHeight);
			}
		}
		
		/**
		 * 载入页面
		 * @param	pageIndex
		 */
		public function loadPage(pageInfo:PageInfo):void 
		{
		
			//__currentPageInfo = pageInfo;
			cleanCurrentPage(pageInfo);
		}
		
		/**
		 * 在载入子页面前触发
		 */
		protected function beforeLoadChild():void 
		{
			
		}
		
		/**
		 * 在子页面载入完成后触发
		 * @param	success	是否载入成功
		 */
		protected function afterLoadChild(success:Boolean):void 
		{
			
		}
		
		/**
		 * 载入根目录
		 */
		protected function __load():void 
		{
		
			beforeLoadChild();
			showLoadBar();
			
			var page:PageInfo = getRootPageInfo(__currentPageInfo);
		
			WebRequest.getInstance().singleLoad(page.pageURL, 
										  WebRequest.TYPE_SWF, 
										  onLoadPageComplete,
										  onLoadPageProgress,
										  onLoadPageFailed);
		}

		
		/**
		 * 现在载入进度条
		 */
		protected function showLoadBar():void 
		{	
			
			clearTimeout(__timeOut);
			if (__loadBar == null)
			{
				try
				{
					var ref:Class;
					if (( ref = this.loaderInfo.applicationDomain.getDefinition("SelfLoad") as Class) 
					!= null)
					{
						
						__loadBar = new ref() as BaseLoadbar;
						__loadBar.resize(stage.stageWidth, stage.stageHeight);
					}
				}
				catch (e:*)
				{
					//
				}
			}
			if (__loadBar != null)
			{
				if (__loadBar.parent)
				{
					
				}
				else
				{
					addChild(__loadBar);
					__loadBar.visible = false;
					__timeOut = setTimeout(viewLoadbar, 200);
				}
				__loadBar.percent = 0;	
			}
		}
		
		/**
		 * 显示进度条
		 */
		private function viewLoadbar():void
		{
			
			if (__loadBar)
			{
				__loadBar.visible = true;
			}
		}
		
		protected function hideLoadBar():void 
		{
			clearTimeout(__timeOut);
			if (__loadBar && __loadBar.parent)
			{
				removeChild(__loadBar);
			}
		}
		
		/**
		 * 添加子元素
		 */
		protected function addChildren():void 
		{
			showLoadBar();
		
			WebRequest.getInstance().singleLoad(WebConfig.getInstance().getChildrenName(),
												WebRequest.TYPE_SWF,
												onLoadChildrenComplete,
												onLoadChildrenProgress,
												onLoadChildrenFailed);
		}
		
		/**
		 * 初始化首页子元素，把它添加到舞台
		 */
		protected function initChildren():void 
		{
			if (__children == null)
			{
				return;
			}
			
			__children.regiNav(WebConfig.getInstance().config);
			__children.addEventListener(Page.FADIN, onMainChildrenFadin);
			__children.resize(stage.stageWidth, stage.stageHeight);
			addChild(__children);
			__children.fadIn();
		
		}
		
		/**
		 * 首页子元素进场完成后触发
		 * @param	event
		 */
		protected function onMainChildrenFadin(event:Event):void 
		{
			invalidate();
		}
		
		/**
		 * 当首页子元素载入完成后触发
		 * @param	data
		 */
		protected function onLoadChildrenComplete(data:*):void 
		{
			hideLoadBar();
			__children = MainChildren(data);
			initChildren();
		}
		
		/**
		 * 首页子元素载入进度变化时触发
		 * @param	bytesLoaded		载入进度
		 * @param	bytesTotal		总进度
		 */
		protected function onLoadChildrenProgress(bytesLoaded:Number, bytesTotal:Number):void 
		{
			if (__loadBar)
			{
				__loadBar.percent =  Math.floor(bytesLoaded / bytesTotal * 100);
			}
		}
		
		/**
		 * 当首页子元素载入失败后触发
		 */
		protected function onLoadChildrenFailed():void 
		{
			throw new Error("Load main children failed, pleace check the web config");;
		}
		
		/**
		 * 渲染页面
		 * @param	page
		 */
		protected function renderPage(page:Page):void 
		{
			if (__currentPage != null && __currentPage.parent != null)
			{
				__currentPage.removeEventListener(Page.FADIN, onPageFadIn);
				__currentPage.removeEventListener(Page.FADOUT, onPageFadOut);
				removeChild(__currentPage);
				
			}
			__currentPage = page;
			page.selfInfo = getRootPageInfo(__currentPageInfo);
			addChild(page);
			page.addEventListener(Page.FADIN, onPageFadIn);
			page.addEventListener(Page.FADOUT, onPageFadOut);
			page.fadIn();
		
		
			
			if (__children)
			{
				setChildIndex(__children, numChildren - 1);
			}
			
		}
		
		/**
		 * 载入完成后发生
		 * @param	data 页面文件
		 */
		protected function onLoadPageComplete(data:*):void 
		{
			
			hideLoadBar();
			afterLoadChild(true);
			renderPage(Page(data));
		}
	
		
		/**
		 * 载入页面进度变化时发生
		 * @param	bytesLoaded		已载入进度
		 * @param	bytesTotal		总进度
		 */
		protected function onLoadPageProgress(bytesLoaded:Number, bytesTotal:Number):void 
		{
			if (__loadBar)
			{
				__loadBar.percent =  Math.floor(bytesLoaded / bytesTotal * 100);
			}
		}
		
		/**
		 * 当页面载入失败时发生
		 */
		protected function onLoadPageFailed():void 
		{
		
			afterLoadChild(false);
			var info:PageInfo = getRootPageInfo(__currentPageInfo);
			var msg:String = "Load Page:" + info.pageName +  " src(" + info.pageURL + ") failed1";
			throw new Error(msg);
		}
		
		/**
		 * 获取PageInfo的根页面
		 * @param	pageInfo
		 * @return
		 */
		private function getRootPageInfo(pageInfo:PageInfo):PageInfo
		{
			var info:PageInfo = pageInfo;
			while (info.parent != null)
			{
				info = info.parent;
			}
			return info;
		}
		
		
		/**
		 * 清除当前页面(已经载入的，正在载入的)
		 */
		protected function cleanCurrentPage(willLoading:PageInfo):void 
		{
			
			
			if (__currentPageInfo != null && __currentPage != null)
			{
				var child:PageInfo = getRootPageInfo(willLoading);
				__currentPageInfo = willLoading;
				if (child.contains(__currentPage.selfInfo))
				{
					
					
					__currentPage.autoLoadChild(willLoading);
				}
				else 
				{
					
					__currentPage.fadOut();
				}
				
			}
			else 
			{
				__currentPageInfo = willLoading;
				__load();
			}
		}
		

		
		
		/**********************************************************/
		/*===                                                  ===*/
		/*===                 event handlers                   ===*/
		/*===                                                  ===*/
		/**********************************************************/
		
		/**
		 * 当舞台大小变化事触发
		 * @param	event
		 */
		private function onStageResize(event:Event):void 
		{
			resize(stage.stageWidth, stage.stageHeight);
		}
		
		/**
		 * 当网站配置文件载入完成后触发
		 * @param	event
		 */
		protected function onWebConfigInit(event:Event):void 
		{
			WebConfig.getInstance().register(this);
			
			if (WebConfig.getInstance().getChildrenName() != null)
			{
				addChildren();
			}
			else 
			{
				invalidate();	
			}
		}
		
		/**
		 * 当页面渐现完成时触发
		 * @param	event
		 */
		protected function onPageFadIn(event:Event):void 
		{
			
			__currentPage.autoLoadChild(__currentPageInfo);
		}
		
		/**
		 * 当页面渐隐完成时触发
		 * @param	event
		 */
		protected function onPageFadOut(event:Event):void 
		{
			var page:Page = event.target as Page;
			page.removeEventListener(Page.FADIN, onPageFadIn);
			page.removeEventListener(Page.FADOUT, onPageFadOut);
		
			
			removeChild(page);
			__currentPage = null;
			__load();
			
			//System.gc();
		}
	}

}